package com.xxxx.rpc.service.impl;

import com.xxxx.common.base.RespBean;
import com.xxxx.common.pojo.Admin;
import com.xxxx.common.utils.JsonUtil;
import com.xxxx.rpc.service.CartService;
import com.xxxx.rpc.vo.CartResult;
import com.xxxx.rpc.vo.CartVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//购物车的实现类
@Service(interfaceClass = CartService.class)
@Component
public class CartServiceImpl implements CartService {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Value("${user.cart}")
    private String userCart;

    //加入购物车
    @Override
    public BaseResult addCart(CartVo cartVo, Admin admin) {
        //如果用户信息不存在，直接返回
        if(null==admin||null==admin.getAdminId()){
            return BaseResult.error();
        }

        Short userId = admin.getAdminId();
        //查询当前用户的购物车信息
        HashOperations<String, String, String> hashOperations =redisTemplate.opsForHash();
        Map<String, String> cartMap = hashOperations.entries(userCart + ":" + userId);
        if(!CollectionUtils.isEmpty(cartMap)){
            //如果购物车信息不为空，修改购物车的信息
            //根据商品ID获取购物车信息
            String cartStr = cartMap.get(String.valueOf(cartVo.getGoodsId()));
            //如果商品存在，就要修改商品的数量和价格
            if(!StringUtils.isEmpty(cartStr)){
                CartVo vo = JsonUtil.jsonStr2Object(cartStr, CartVo.class);
                //修改商品数量
                vo.setGoodsNum(vo.getGoodsNum()+ cartVo.getGoodsNum());
                //修改商品的价格
                vo.setMarketPrice(cartVo.getMarketPrice());
                //重新添加，覆盖之前的商品对象
                cartMap.put(String.valueOf(vo.getGoodsId()), JsonUtil.object2JsonStr(vo));
            }else{
                //如果商品存在，添加购物车信息
                cartMap.put(String.valueOf(cartVo.getGoodsId()), JsonUtil.object2JsonStr(cartVo));
            }
        }else{
            //如果购物车信息为空，新增购物车信息
            cartMap = new HashMap<>();
            cartMap.put(String.valueOf(cartVo.getGoodsId()), JsonUtil.object2JsonStr(cartVo));
        }
        hashOperations.putAll(userCart+":"+userId,cartMap);
        return BaseResult.success();
    }
    //清除购物车
    @Override
    public BaseResult clearCart(Admin admin) {
        //判断用户是否存在
        if (null==admin||null==admin.getId()){
            return null;
        }
        //获取购物车信息
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
        Map<String, String> cartMap = hashOperations.entries(userCart + ":" + admin.getId());
        if (CollectionUtils.isEmpty(cartMap)){
            return BaseResult.error();
        }
        redisTemplate.delete(userCart+":"+admin.getId());
        return BaseResult.success();
    }

    //查询购物车
    @Override
    public Integer getCartNum(Admin admin) {
        //判断admin是否登录
        if(null==admin||null==admin.getAdminId()){
            return 0;
        }
        //购物车数量初始为0
        Integer result = 0;
        HashOperations<String, String, String> hashOperations =redisTemplate.opsForHash();
        Map<String, String> cartMap = hashOperations.entries(userCart + ":" + admin.getAdminId());
        //如果购物车信息不为空，累加购物车数量
        if(!CollectionUtils.isEmpty(cartMap)){
            for (Map.Entry<String, String> entry : cartMap.entrySet()) {
                CartVo cartVo = JsonUtil.jsonStr2Object(entry.getValue(), CartVo.class);
                result += cartVo.getGoodsNum();

            }
        }
        return result;
    }


    /*获取购物车列表*/
    @Override
    public CartResult getCartList(Admin admin) {
       //判断用户是否存在
        if(null==admin||null==admin.getAdminId()){
            return null;
        }
        //初始化返回对象
        CartResult cartResult = null;
        //从Redis获取购物车信息
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
        Map<String, String> cartMap = hashOperations.entries(userCart + ":" + admin.getAdminId());
        //判断是否存在购物车信息
        if(!CollectionUtils.isEmpty(cartMap)){
            cartResult = new CartResult();
            //购物车列表
            List<CartVo> cartList = cartMap.values().stream().map(e -> JsonUtil.jsonStr2Object(e, CartVo.class)).collect(Collectors.toList());
            //总价
            BigDecimal totalPrice = cartList.stream().map(e->e.getMarketPrice().multiply(new BigDecimal(String.valueOf(e.getGoodsNum())))).reduce(BigDecimal.ZERO,BigDecimal::add);
            totalPrice.setScale(2,BigDecimal.ROUND_HALF_UP);
            cartResult.setCartList(cartList);
            cartResult.setTotalPrice(totalPrice);
        }
        return cartResult;
    }
}
